package com.mallfoundry.store;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CustomCollectionService {

    private final CustomCollectionRepository customCollectionRepository;

    public CustomCollectionService(CustomCollectionRepository customCollectionRepository) {
        this.customCollectionRepository = customCollectionRepository;
    }

    @Transactional
    public TopCustomCollection createTopCollection(StoreId storeId, String name) {
        TopCustomCollection collection =
                this.customCollectionRepository.save(new TopCustomCollection(storeId, name));
        CustomCollectionPositions.sort(this.customCollectionRepository.findAll(storeId));
        return collection;
    }

    @Transactional
    public ChildCustomCollection addChildCollection(Integer parentId, String name) {
        CustomCollection collection = this.getCollection(parentId);
        ChildCustomCollection childCollection = new ChildCustomCollection(name);
        collection.addChildCollection(childCollection);
        return childCollection;
    }

    @Transactional
    public void deleteCollection(Integer id) {
        this.customCollectionRepository.deleteById(id);
    }

    @SuppressWarnings("unchecked")
    public <S extends CustomCollection> S getCollection(Integer id) {
        return (S) customCollectionRepository.findById(id);
    }

    public List<CustomCollection> getAllCollections(StoreId storeId) {
        return this.customCollectionRepository.findAll(storeId);
    }

}
